﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace xycn.datacache
{
    /// <summary>
    /// 周期任务
    /// </summary>
    public class QuartzWork
    {
        //调度器
        static IScheduler scheduler;
        //调度器工厂
        static ISchedulerFactory factory;

        //0 0/1 * * * ?
        public async void Start()
        {
            //初始化调度器
            factory = new StdSchedulerFactory();
            scheduler = await factory.GetScheduler();
            await scheduler.Start();

            IJobDetail stockJob = JobBuilder.Create<CacheJob>().WithIdentity("stockIdentity", "group1").Build();
            ITrigger stockTrigger = TriggerBuilder.Create().WithIdentity("stockTrigger", "group1").WithCronSchedule("0 0/1 * * * ?").Build();
            await scheduler.ScheduleJob(stockJob, stockTrigger);
        }
    }

    public class CacheJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var delkeys = DataValues.CacheExTime.Where(p => p.Value < DateTime.Now).Select(p=>p.Key).ToList();

            foreach (var item in delkeys)
            {
                DataValues.CacheData.Remove(item);
                DataValues.CacheExTime.Remove(item);
            }
            return Task.CompletedTask;
        }
    }
}
